package com.sciai.controller;

import cn.com.sciai.aix.common.http.SciaiHttpResponseEntity;
import cn.com.sciai.aix.common.http.SciaiHttpResponseEntityBuilder;
import cn.com.sciai.aix.common.http.page.SciaiPageEntity;
import cn.com.sciai.aix.common.http.page.SciaiPageEntityBuilder;
import cn.com.sciai.aix.common.http.page.SciaiPageRequestEntity;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.csvreader.CsvReader;
import com.fasterxml.uuid.EthernetAddress;
import com.fasterxml.uuid.Generators;
import com.fasterxml.uuid.impl.TimeBasedGenerator;
import com.sciai.Service.CsvDataService;
import com.sciai.Service.FilePathService;
import com.sciai.Service.TBusinessService;
import com.sciai.entity.CsvData;
import com.sciai.entity.FilePath;
import com.sciai.entity.Weather;
import com.sciai.entity.WeatherType;
import com.sciai.entity.req.*;
import com.sciai.entity.vo.CsvDataVo;
import com.sciai.mapper.WeatherMapper;
import com.sciai.utils.AddressUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/business")
@Validated
public class BusinessController {

    @Value("${file.imagPath}")
    private String imagPath;
    @Value("${file.videoPath}")
    private String videoPath;
    @Resource
    private TBusinessService tBusinessService;
    @Resource
    private FilePathService filePathService;
    @Resource
    private WeatherMapper weatherMapper;
    @Resource
    private CsvDataService csvDataService;
    @Value("${file.csvFile1}")
    private String csvFile1;
    @Value("${file.csvFile2}")
    private String csvFile2;

    @Value("${file.csvFile3}")
    private String csvFile3;

    /**
     * 生成任务信息
     *
     * @return
     */
    @PostMapping("/generateTask")
    public SciaiHttpResponseEntity generateTask(@Validated @RequestBody BusinessGenerateReq req) {


        return tBusinessService.generateTask(req);
    }

    /**
     *上传图片
     *
     * @param uploadFiles
     * @return
     */
    @PostMapping("/imagUpload")
    public SciaiHttpResponseEntity imagUpload(@RequestParam("file")  MultipartFile[] uploadFiles ,@RequestParam("uuid") String uuid,@RequestParam("id") String id) throws IOException {
        try {
            Map<String,Object> objectMap =new HashMap<>();
            List<String> list1 = new ArrayList<>();
            //1，对文件数组做判空操作
            if (uploadFiles == null && uploadFiles.length < 1) {
                return SciaiHttpResponseEntityBuilder.builder().error("500","文件为空！请检查！").build();
            }
            TimeBasedGenerator generator = Generators.timeBasedGenerator(EthernetAddress.fromInterface());
            String uuidStr="";
            if (uuid.equals("") || uuid.equals("null")){
                //该次填报信息是第一上传文件
                UUID uuidNew = generator.generate();
                uuidStr = uuidNew.toString();
            }else {
                //该次填报信息不是第一次上传数据
                uuidStr=uuid;
            }
            List<FilePath> list =new ArrayList<>();
            //3，遍历文件数组，一个个上传
            for (int i = 0; i < uploadFiles.length; i++) {
                MultipartFile file = uploadFiles[i];
                //时间戳加 文件原名  生成为新文件名
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
                String previousDay = dateFormat.format(new Date());
                TimeBasedGenerator generator2 = Generators.timeBasedGenerator(EthernetAddress.fromInterface());
                UUID uuid2 = generator2.generate();
                // 获取后缀
                String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                String fileName = previousDay+"_"+uuid2+fileSuffix;
                String filePath2 = imagPath+fileName;

                FilePath filePath =new FilePath();
                filePath.setCreateTime(new Date());
                filePath.setUuid(uuidStr);
                filePath.setCreateUserId(Integer.valueOf(id));
                filePath.setPath(fileName);
                File localFlie = new File(filePath2);
                file.transferTo(localFlie);

                // base64图片前缀
                byte[] baseByte= new byte[0];
                String pre = "data:image/jpg;base64,";
                // 读取图片
                FileInputStream fileInputStream = new FileInputStream(localFlie);
                // 读取字节长度
                int len = 0;
                // baseByte数组的容量
                int capacity = 0;
                byte [] bytes = new byte[1024];
                while ((len = fileInputStream.read(bytes)) != -1){
                    // 对原数组进行拷贝扩容
                    baseByte= Arrays.copyOf(baseByte, len + capacity);
                    // 将新数据拷贝到新扩容的数组
                    System.arraycopy(bytes, 0, baseByte, capacity, len);
                    // 数据容量增加
                    capacity += len;
                }
                fileInputStream.close();
                // 获取base64编码器
                Base64.Encoder encoder = Base64.getEncoder();
                // 将字节数组转换base64
                String encodeToString = encoder.encodeToString(baseByte);
                String strImage = pre+encodeToString;
                list1.add(strImage);
                list.add(filePath);
            }
            objectMap.put("uuid",uuidStr);
            objectMap.put("list",list1);
            if (filePathService.saveBatch(list)){
                return SciaiHttpResponseEntityBuilder.builder().ok(objectMap).build();
            }else {
                return SciaiHttpResponseEntityBuilder.builder().error("500", "系统出错！").build();
            }
        }catch (Exception e){
            return SciaiHttpResponseEntityBuilder.builder().error("500", "系统出错！" + e.getMessage()).build();
        }
    }

    /**
     * 上传视频文件
     *
     * @param file
     * @return
     */
    @PostMapping("/videoUpload")
    public SciaiHttpResponseEntity videoUpload(@RequestParam("file") MultipartFile file,@RequestParam("uuid") String uuid,@RequestParam("id") String id) throws IOException {
        try {
            TimeBasedGenerator generator = Generators.timeBasedGenerator(EthernetAddress.fromInterface());
            String uuidStr="";
            if (uuid.equals("") || uuid.equals("null")){
                //该次填报信息是第一上传文件
                UUID uuidNew = generator.generate();
                uuidStr = uuidNew.toString();
            }else {
                //该次填报信息不是第一次上传数据
                uuidStr=uuid;
            }
            //时间戳加 文件原名  生成为新文件名
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
            String previousDay = dateFormat.format(new Date());
            TimeBasedGenerator generator2 = Generators.timeBasedGenerator(EthernetAddress.fromInterface());
            UUID uuid2 = generator2.generate();
            // 获取后缀
            String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String fileName = previousDay+"_"+uuid2+fileSuffix;
//            String fileName = System.currentTimeMillis()+file.getOriginalFilename();
            String filePath2 = videoPath+fileName;

            FilePath filePath =new FilePath();
            filePath.setCreateTime(new Date());
            filePath.setUuid(uuidStr);
            filePath.setPath(fileName);
            filePath.setCreateUserId(Integer.valueOf(id));
            if (filePathService.save(filePath)){

                File localFlie = new File(filePath2);
                file.transferTo(localFlie);
                return SciaiHttpResponseEntityBuilder.builder().ok(uuidStr).build();
            }else {
                return SciaiHttpResponseEntityBuilder.builder().error("500", "系统出错！").build();
            }
        }catch (Exception e){
            return SciaiHttpResponseEntityBuilder.builder().error("500", "系统出错！" + e.getMessage()).build();
        }
    }



    /**
     * 查询天气信息
     *
     * @return
     */
    @PostMapping("/queryWeather")
    public SciaiHttpResponseEntity queryWeather(@Validated @RequestBody WeatherQueryReq req) {
        try {
            //先判断游客身份的校验
            if (req.getType().equals("0")){
                //游客身份校验 所选时间 是否在当前日期和小时--到三天前的小时
                Date date=new Date();
                Calendar calendar =new GregorianCalendar();
                calendar.setTime(date);
                //往前推一天
                calendar.add(Calendar.DATE,-1);
                Date date1=calendar.getTime();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if(date1.after(req.getOccurrenceTime()))
                {
                    //选择查询的时间晚于当前时间或者 查询时间 早于当前时间的前一天时间
                    return SciaiHttpResponseEntityBuilder.builder().error("500", "游客身份查询时间出错！").build();
                }
            }
            Calendar calendar =new GregorianCalendar();
            calendar.setTime(req.getOccurrenceTime());
            //往前推一天  得到开始时间
            calendar.add(Calendar.DATE,-1);
            Date date1=calendar.getTime();  //开始时间
            Date date2=req.getOccurrenceTime(); //结束时间

            return tBusinessService.queryWeather(date1,date2,req.getType());
        }catch (Exception e){
            return SciaiHttpResponseEntityBuilder.builder().error("500", "系统出错！" + e.getMessage()).build();
        }
    }

    @GetMapping("/getGeo")
    public SciaiHttpResponseEntity getGeo() throws IOException {
        double longitude = 123.429441;
        double latitude = 41.83544;
        String addressInfo = AddressUtil.getProvinceCityDistrict(longitude, latitude);
        String[] parts = addressInfo.split(", "); // 拆分成 "City:大连市" 和 "District:甘井子区"
        String city = "";
        String district = "";
        String province = "";
        for (String part : parts) {
            if (part.startsWith("City:")) {
                city = part.substring("City:".length()); // 获取 "市"
            } else if (part.startsWith("District:")) {
                district = part.substring("District:".length()); // 获取 "区"
            } else if (part.startsWith("Province:")) {
                province = part.substring("Province:".length()); // 获取 "省"
            }
        }
        System.out.println(longitude+","+latitude+"的城市区县为:"+addressInfo);
        System.out.println(longitude+","+latitude+"的城市区县为:"+addressInfo);
        System.out.println("Province: " + province);
        System.out.println("City: " + city);
        System.out.println("District: " + district);
        return SciaiHttpResponseEntityBuilder.builder().ok(addressInfo).build();
    }

    @GetMapping("/queryWeatherType")
    public SciaiHttpResponseEntity queryWeatherType()  {
        try {
            Map<String, Object> params2 = new HashMap<>();
            params2.put("isShow",1);
            List<WeatherType> weatherTypes = weatherMapper.queryWeatherType(params2);
            if (weatherTypes.size()==0){
                return SciaiHttpResponseEntityBuilder.builder().error("500", "没有天气类型的基础数据！").build();
            }
            List<LinkedHashMap<String,Object>> mapList =new ArrayList<>();
            for (int i = 0 ; i < weatherTypes.size(); i++){
                LinkedHashMap<String,Object> map =new LinkedHashMap<>();
                map.put("name",weatherTypes.get(i).getTypeName());
                map.put("id",weatherTypes.get(i).getId());
                mapList.add(map);
            }

            return SciaiHttpResponseEntityBuilder.builder().ok(mapList).build();
        }catch (Exception e){
            return SciaiHttpResponseEntityBuilder.builder().error("500", "系统出错！" + e.getMessage()).build();
        }
    }

//    统计
    @PostMapping("/getStatistics")
    public SciaiHttpResponseEntity getStatistics(@Validated @RequestBody TongjieQueryReq req) {
        try {

            //查询天气类型
            Map<String, Object> params2 = new HashMap<>();
            List<WeatherType> weatherTypes = weatherMapper.queryWeatherType(params2);
            if (weatherTypes.size()==0){
                return SciaiHttpResponseEntityBuilder.builder().error("500", "没有天气类型的基础数据！").build();
            }

            Map<String, Object> params = new HashMap<>();
            String starStr = req.getStarTime().toString()+" 00:00:00";
            Date date1 = DateUtil.parse(starStr, "yyyy-MM-dd HH:mm:ss");
            Calendar calendar =new GregorianCalendar();
            calendar.setTime(date1);
            //往前后推一天
            calendar.add(Calendar.DATE,1);
            Date date2=calendar.getTime();

            params.put("date1",date1);
            params.put("date2",date2);
            List<Weather> list = weatherMapper.queryWeather(params);
            Map<String,Object> reusltMap = new HashMap<>();
            List<String>  provinces =new ArrayList<>();
            Map<String, List<Weather>> newMap3 = list.stream().collect(Collectors.groupingBy(Weather::getWeatherTypeName));  //按每种天气
            newMap3.forEach((key, value) -> {
                provinces.add(key);
            });
            reusltMap.put("categories",provinces);
            List<Map<String,Object>> list1 = new ArrayList<>();
            Map<String, List<Weather>> newMap = list.stream().collect(Collectors.groupingBy(Weather::getOccurrencePlace));  //按每种天气
            newMap.forEach((key, value) -> {
                Map<String,Object>  provinceNameNum =new HashMap<>();
                Integer [] integers=new Integer[provinces.size()];
                for (int h = 0 ; h< provinces.size();h++){
                    integers[h]=0;
                }
                Map<String, List<Weather>> newMap2 = value.stream().collect(Collectors.groupingBy(Weather::getWeatherTypeName));  //按每个省份
                newMap2.forEach((key2, value2) -> {
                    provinceNameNum.put("name",key);
                    int index=0;
                    for (int i =0; i<provinces.size();i++){
                        if (key2.equals(provinces.get(i))){
                            //是该省份则记住下标
                            index=i;
                            break;
                        }
                    }
                    integers[index]=value2.size();
                });
                provinceNameNum.put("data",integers);
                list1.add(provinceNameNum);
            });
            reusltMap.put("series",list1);

            return SciaiHttpResponseEntityBuilder.builder().ok(reusltMap).build();

        }catch (Exception e){
            return SciaiHttpResponseEntityBuilder.builder().error("500", "系统出错！" + e.getMessage()).build();
        }
    }

    @PostMapping("/csvData")
    public SciaiHttpResponseEntity queryCsvData(@RequestBody SciaiPageRequestEntity page)  {
        try {

            //查询天气类型
            Map<String, Object> params2 = new HashMap<>();
            List<WeatherType> weatherTypes = weatherMapper.queryWeatherType(params2);
            if (weatherTypes.size()==0){
                return SciaiHttpResponseEntityBuilder.builder().error("500", "没有天气类型的基础数据！").build();
            }

            CsvDataReq req = new CsvDataReq();
            req.setCurrent(page.getCurrentPage());
            req.setSize(page.getPageSize());
            req.setCheck(2);  //查询待审核的
            req.setOccurrenceTime(new Date());
            Page<CsvData> page1 = weatherMapper.findAllByReq(req);
            List<CsvData> listVos =  page1.getRecords();

            List<CsvDataVo> voList =new ArrayList<>();
            for (CsvData csvData : listVos){
                CsvDataVo vo = new CsvDataVo();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String time = simpleDateFormat.format(csvData.getOccurrenceTime());
                String a =time+" "+csvData.getContent();
                String c ="";
                for (int j = 0 ; j < weatherTypes.size();j++){
                    if (weatherTypes.get(j).getId()==csvData.getWeatherType()){
                        c=weatherTypes.get(j).getTypeName();
                    }
                }
                String b =time+" "+csvData.getOccurrenceProvince()+csvData.getOccurrenceCity()+" ("+csvData.getLon()+","+csvData.getLat()+")"+c;
                vo.setContent(a);
                vo.setPlace(b);
                vo.setId(csvData.getId());
                voList.add(vo);
            }

            SciaiPageEntity entity = SciaiPageEntityBuilder.builder()
                    .data(voList)
                    .currentPage(page1.getCurrent())
                    .pageSize(page1.getSize())
                    .totalCount(page1.getTotal())
                    .totalPage(page1.getPages())
                    .build();

            return SciaiHttpResponseEntityBuilder.builder().ok(entity).build();
        }catch (Exception e){
            return SciaiHttpResponseEntityBuilder.builder().error("500",e.toString()).build();
        }
    }


    @PostMapping("/csvDataCheck")
    public SciaiHttpResponseEntity csvDataCheck(@RequestBody CsvDataCheckReq csvDataCheckReq)  {
        try {
            int a= Integer.parseInt(csvDataCheckReq.getId());
            CsvData csvData =  csvDataService.getById(a);
            if (csvData==null){
                return SciaiHttpResponseEntityBuilder.builder().error("500","查询不到原数据！").build();
            }
            csvData.setCheckIs(Integer.valueOf(csvDataCheckReq.getCheck()));
            if(csvDataService.saveOrUpdate(csvData)){
                return SciaiHttpResponseEntityBuilder.builder().ok("审核成功！").build();
            }else {
                return SciaiHttpResponseEntityBuilder.builder().error("500","审核失败！").build();
            }
        }catch (Exception e){
            return SciaiHttpResponseEntityBuilder.builder().error("500",e.toString()).build();
        }
    }
    @PostMapping("/operateDelete")
    public SciaiHttpResponseEntity operateDelete(@RequestBody Operate operate)  {
        try {

            String starStr = operate.getDate()+" 00:00:00";
            Date date1 = DateUtil.parse(starStr, "yyyy-MM-dd HH:mm:ss");
            Calendar calendar =new GregorianCalendar();
            calendar.setTime(date1);
            //往后推一天查询当前选择的当天的数据导出
            calendar.add(Calendar.DATE,1);
            Date date2=calendar.getTime();
            String data3 =DateUtil.format(date2,"yyyy-MM-dd HH:mm:ss");
            Date date4 = DateUtil.parse(data3, "yyyy-MM-dd HH:mm:ss");
            Map<String, Object> params2 = new HashMap<>();
            params2.put("date1",date1);
            params2.put("date2",date4);
            List<Weather> weathers = weatherMapper.findAllTypeByParams(params2);
            Map<String, Object> params = new HashMap<>();
            params.put("date1",date1);
            params.put("date2",date4);
            List<CsvData> list = weatherMapper.findAllByParams(params);
            if (weathers.size()!=0){
                List<Integer> list1 = weathers.stream().map(f -> f.getId()).distinct().collect(Collectors.toList());
                if (tBusinessService.removeBatchByIds(list1)){
                    if (list.size()>0){
                        List<Integer> list2 = list.stream().map(f -> f.getId()).distinct().collect(Collectors.toList());
                        if (!csvDataService.removeBatchByIds(list2)){
                            return SciaiHttpResponseEntityBuilder.builder().error("500","清除对应数据失败").build();
                        }
                    }
                }else {
                    return SciaiHttpResponseEntityBuilder.builder().error("500","清除对应数据失败").build();
                }
            }
            return SciaiHttpResponseEntityBuilder.builder().ok("清除对应数据完成！").build();
        }catch (Exception e){
            return SciaiHttpResponseEntityBuilder.builder().error("500",e.toString()).build();
        }
    }

    @PostMapping("/operateImport")
    public SciaiHttpResponseEntity operateImport(@RequestBody Operate operate)  {
        SciaiHttpResponseEntity entity = csvDataService.CSVImport2(csvFile1,operate.getDate());
        if (entity.getIsOk()){
            SciaiHttpResponseEntity entity2 = csvDataService.CSVImport2(csvFile2,operate.getDate());
            if (entity2.getIsOk()){
                SciaiHttpResponseEntity entity3 = csvDataService.CSVImport2(csvFile3,operate.getDate());
                if (entity3.getIsOk()){
                    return SciaiHttpResponseEntityBuilder.builder().ok("导入最新的选择日的数据！").build();
                }else {
                    return entity3;
                }
            }else {
                return entity2;
            }
        }else {
            return entity;
        }
    }


}
